const base = require("./base");
const Tplmsg = require("./../../../../lib/wxa/tplmsg.class");

module.exports = class extends base {
    async _initialize() {
        await super.isWxaAuth();
    }

    async _before() {
        this.tplMsg = new Tplmsg(
            process.env.OPEN_APPID,
            process.env.OPEN_APPSECRET
        );
        this.state.wxa = await this.checkWxaAuthorizerAccessToken(
            this.state.wxa
        );
    }

    /**
     *
     * @api {post} /api/tplmsg/sendTplMsg 发送模版消息
     * @apiDescription 发送模版消息
     * @apiGroup App Api
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Referer 小程序referer
     *
     * @apiParam {String} openid openid
     * @apiParam {Number} tpl_id tpl_id
     * @apiParam {Number} form_id form_id
     * @apiParam {String} data 数据
     * @apiParam {String} page 点击模版消息跳转
     * @apiParam {String} keyword 关键词
     *
     * @apiSuccess {Object} success 发送模版消息结果
     *
     * @apiSampleRequest /api/tplmsg/sendTplMsg
     *
     */
    async sendTplMsg() {
        const {
            openid,
            tpl_id,
            form_id,
            data = "",
            page = "",
            keyword = ""
        } = this.post;

        const result = await this.tplMsg.send_tplmsg(
            this.state.wxa.authorizer_access_token,
            openid,
            tpl_id,
            form_id,
            data,
            page,
            keyword
        );
        if (result.errormsg === "ok") {
            this.success("发送成功");
        } else {
            this.fail(this.tplMsgErr(result));
        }
    }
};
